var mongoose = require('mongoose');
var Cate = require('../models/cate.model')//引数据模型；


exports.create = function(req,res,next){
    var cate = new Cate(req.body);
    cate.save()
    .then(data=>{
        res.json(data)
    })
}

exports.update = function(req,res,next){
    
      var id = req.params.id; // req.param('id')
      // 现在操作的都是mongoose而不是mongodb
      Cate.findByIdAndUpdate(id,{$set: req.body}, {new:false} )
      .then(data=>{
          res.json({msg:'数据修改成功',status:200}); // 如果你要返回数据，这个data返回的是你之前修改的那个数据内,
      })
  }


	function reverseTree(data,pid){
		var result = [],
		temp;
		var data = JSON.parse( JSON.stringify(data));
		
		for(var i in data){
			if(data[i].parentId === pid){
				result.push(data[i]);
				
				temp = reverseTree(data,data[i]._id);
				if(temp.length>0){
					data[i].children = temp;
				}
			}
		}
		
		return result;
	}

exports.list = function(req,res,next){
	Cate.find({},function(err,data){
		var rpTree = reverseTree(data,null);
		res.json(rpTree)
	})
}


exports.remove = function(req,res,next){
	var id = req.params.id;
	
	var ids = [];
	
	Cate.findOne({_id:id},function(err,doc){
		if(doc){
			ids = [doc._id];
			
			doc.getChildren().then(function(docs){
				for(var i=0;i<docs.length;i++){
					ids.push(docs[i]._id)
				}
				Cate.remove({_id:{$in:ids}})
				.then(data=>{
					res.json({'msg':"数据删除成功",status:200})
				})
			})
		}
	})
}
